package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class HttpRequest {
    private String method;
    private String uri;
    private String protocol;
    private String requestURI;
    private String queryString;
    private Map<String,String> parameters =new HashMap<>();
    private  Map<String,String> headers=new HashMap<>();
    private Socket socket;
    public HttpRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket=socket;
        parseRequestLine();
        parseHeaders();
        parseContent();
    }
    private void parseRequestLine() throws IOException, EmptyRequestException {
        String line =readLine();
        if (line.isEmpty()){
            throw new EmptyRequestException();
        }
        System.out.println(line);
        String[] data =line.split("\\s");
        method=data[0];
        uri=data[1];
        protocol=data[2];
        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
        parseURI();
    }
    private void parseURI(){
        String[] arr =uri.split("\\?");
        requestURI =arr[0];
        if (arr.length>1){
            queryString =arr[1];
            parseParameters(queryString);
        }
        System.out.println("requestURI:"+requestURI);
        System.out.println("queryString:"+queryString);
        System.out.println("parameters:"+parameters);
    }
    private void parseParameters(String line){
        String[] paras =line.split("&");
        for (String para:paras){
            String[] data =para.split("=");
            if (data.length>1){
                parameters.put(data[0],data[1]);
            }else {
                parameters.put(data[0],null);
            }
        }
    }
    private void parseHeaders() throws IOException {
        String line;
        String[] data;
        while(!(line=readLine()).isEmpty()){
            System.out.println("消息头："+line);
            data =line.split(":\\s");
            headers.put(data[0].toLowerCase(),data[1]);
        }
        System.out.println("headers:"+headers);
    }
    private void parseContent(){
        if ("post".equalsIgnoreCase(method)){
            String lengthStr =headers.get("content-length");
            if (lengthStr!=null){
                int length =Integer.parseInt(lengthStr);
                byte[] data =new byte[length];
                try{
                    InputStream in =socket.getInputStream();
                    in.read(data);
                }catch (IOException e){
                    e.printStackTrace();
                }
                String contentType =headers.get("content-type");
                if ("application/x-www-form-urlencoded".equals(contentType)){
                    try {
                        String line = new String(data,"ISO8859-1");
                        System.out.println("正文内容："+line);
                        parseParameters(line);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    private String readLine() throws IOException {
        InputStream in =socket.getInputStream();
        StringBuilder builder =new StringBuilder();
        int d ;
        char pre ='a',cur='a';
        while((d=in.read())!=-1){
            cur =(char)d;
            if (pre==13 &&cur==10){
                break;
            }
            builder.append(cur);
            pre=cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }
    public String getHeader(String name){
        return headers.get(name);
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    public String getParameter(String name) {
        String value =parameters.get(name);
        try {
            if (value!=null) {
                return URLDecoder.decode(value, "UTF-8");

            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return value;
    }
}
